package com.mxnet.chongjin.nci.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mxnet.chongjin.nci.R;
import com.mxnet.chongjin.nci.base.BaseActivity;
import com.mxnet.chongjin.nci.bean.Cause;
import com.mxnet.chongjin.nci.bean.Inventory;
import com.mxnet.chongjin.nci.config.Api;
import com.mxnet.chongjin.nci.utils.CustomCallBack;
import com.mxnet.chongjin.nci.utils.StringUtils;
import com.mxnet.chongjin.nci.view.ItemInventorySaveView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class ManageMoveInventorySaveActivity extends BaseActivity {
    private Context mContext;
    private Button mButtonBack, mButtonSend;
    private EditText mEditTextTitle;
    private TextView mTextViewCause;
    private LinearLayout mLayout;
    private ArrayList<String> mBarcodeList;
    private List<Inventory> mInventoryList;
    private SharedPreferences mPreferences;
    private int pickingId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_move_inventory_save);
        mContext = ManageMoveInventorySaveActivity.this;
        pickingId = getIntent().getIntExtra("pickingId", 0);
        mPreferences = getPreferences();
        mBarcodeList = new ArrayList<>();
        mInventoryList = new ArrayList<>();

        mEditTextTitle = findViewById(R.id.edittext_manage_move_inventory_save_title);
        mEditTextTitle.setHint("请输入标题...");

        mLayout = findViewById(R.id.ll_manage_move_inventory_save_list);

        mTextViewCause = findViewById(R.id.textview_manage_move_inventory_save_cause);
        mTextViewCause.setText(((Cause) getIntent().getSerializableExtra("cause")).getDescribe());

        mBarcodeList = getIntent().getStringArrayListExtra("barcodeList");
        String str = "";
        for (String s : mBarcodeList) {
            str += s;
        }
        Log.i("*****barcodes", str);
        initData();

        mButtonBack = findViewById(R.id.btn_move_inventory_save_back);
        mButtonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mButtonSend = findViewById(R.id.btn_move_inventory_save_send);
        mButtonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpUtils.get()
                        .url(mPreferences.getString("URL_HEADER", "") + Api.SEND_PICKING)
                        .addParams("deviceNo", mPreferences.getString("deviceNo", ""))
                        .addParams("type", "02")
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Log.i("*****==onError==", e.getMessage());
                                StringUtils.beep(mContext);
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean isSuccess = jsonObject.optBoolean("success");
                                        int code = jsonObject.optInt("code");
                                        if (isSuccess && code == 200) {
                                            Toast.makeText(mContext, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(mContext, IndexActivity.class);
                                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                            startActivity(intent);
                                            finish();
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
            }
        });
    }

    public void initData() {
        OkHttpUtils.get()
                .url(mPreferences.getString("URL_HEADER", "") + Api.BARCODE_QUERY_INVENTORY)
                .addParams("barcodes", new Gson().toJson(mBarcodeList))
                .addParams("type", "02")
                .addParams("deviceNo", mPreferences.getString("deviceNo", ""))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("*****==onError==", e.getMessage());
                        StringUtils.beep(mContext);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean isSuccess = jsonObject.optBoolean("success");
                                if (isSuccess) {
                                    JSONArray datas = jsonObject.optJSONArray("data");
                                    for (int i = 0; i < datas.length(); i++) {
                                        JSONObject object = datas.optJSONObject(i);
                                        Inventory inventory = new Inventory();
                                        inventory.setITEM(object.optString("item"));
                                        inventory.setLot(object.optString("lot"));
                                        inventory.setLength(object.optString("length"));
                                        inventory.setWidth(object.optString("width"));
                                        inventory.setQty(object.optInt("count"));
                                        mInventoryList.add(inventory);
                                        ItemInventorySaveView inventorySaveView = new ItemInventorySaveView(mContext, R.layout.item_inventory_save);
                                        inventorySaveView.getTextView1().setText(object.optString("item"));
                                        inventorySaveView.getTextView2().setText(object.optString("length"));
                                        inventorySaveView.getTextView3().setText(object.optString("width"));
                                        inventorySaveView.getTextView4().setText(object.optString("lot"));
                                        inventorySaveView.getTextView5().setText(object.optInt("count") + "");
                                        inventorySaveView.getButton().setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {

                                                //Intent intent = new Intent();
                                                ItemInventorySaveView inventorySaveView = (ItemInventorySaveView) v.getParent().getParent().getParent();
                                                //intent.putExtra("lot", inventorySaveView.getTextView4().getText());
                                                //intent.putExtra("pickingId", pickingId);
                                                //ManageInventorySaveActivity.this.setResult(201, intent);
                                                ManageMoveInventorySaveActivity.this.setResult(201);
                                                OkHttpUtils.get()
                                                        .url(mPreferences.getString("URL_HEADER", "") + Api.DELETE_MOVINGS)
                                                        .addParams("lot", inventorySaveView.getTextView4().getText().toString())
                                                        .addParams("pickingId", pickingId + "")
                                                        .build()
                                                        .execute(new CustomCallBack(inventorySaveView) {
                                                            @Override
                                                            public void onError(Call call, Exception e, int id) {
                                                                Log.i("*****==onError==", e.getMessage());
                                                                StringUtils.beep(mContext);
                                                            }

                                                            @Override
                                                            public void onResponse(String response, int id) {
                                                                if (!TextUtils.isEmpty(response)) {
                                                                    try {
                                                                        JSONObject jsonObject = new JSONObject(response);
                                                                        boolean isSuccess = jsonObject.optBoolean("success");
                                                                        if (isSuccess) {
                                                                            StringUtils.clearNumber(mPreferences, "MoveInventory");
                                                                            mLayout.removeView((ItemInventorySaveView) this.getTag());
                                                                        } else {
                                                                            StringUtils.beep(mContext);
                                                                        }
                                                                    } catch (Exception e) {
                                                                        e.printStackTrace();
                                                                        StringUtils.beep(mContext);
                                                                    }
                                                                }
                                                            }
                                                        });


                                            }
                                        });
                                        mLayout.addView(inventorySaveView, 0);
                                    }
                                } else {
                                    Log.i("*****==onResponse==", response);
                                    StringUtils.beep(mContext);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                StringUtils.beep(mContext);
                            }
                        }
                    }
                });
    }
}
